package com.tys.algorithm.advanced.code.class03;

import java.util.Stack;

/**
 * 两个栈实现队列
 */
public class Code06_TwoStacksImplementQueue {

    public static class TwoStacksQueue {
        //定义push栈和pop栈
        private Stack<Integer> stackPush;
        private Stack<Integer> stackPop;

        public TwoStacksQueue() {
            stackPush = new Stack<Integer>();
            stackPop = new Stack<Integer>();
        }

        // push栈向pop栈倒入数据
        public void pushToPop() {
            if (stackPop.isEmpty()) {
                //pop栈为空则将push栈数据全部导入pop栈
                while (!stackPush.isEmpty()) {
                    stackPop.push(stackPush.pop());
                }
            }
        }

        //入队
        public void add(int value) {
            //入push栈
            stackPush.push(value);
            //从push栈导出数据到pop栈
            pushToPop();
        }

        //出队
        public int poll() {
            //push栈和pop栈都为空则抛异常
            if (stackPop.isEmpty() && stackPush.isEmpty()) {
                throw new RuntimeException("Queue is empty!");
            }
            //从push栈导出数据到pop栈
            pushToPop();
            //弹出pop栈
            return stackPop.pop();
        }

        //弹出
        public int peek() {
            //push栈和pop栈都为空则抛异常
            if (stackPop.isEmpty() && stackPush.isEmpty()) {
                throw new RuntimeException("Queue is empty!");
            }
            //从push栈导出数据到pop栈
            pushToPop();
            //返回pop栈顶
            return stackPop.peek();
        }
    }

    public static void main(String[] args) {
        TwoStacksQueue test = new TwoStacksQueue();
        test.add(1);
        test.add(2);
        test.add(3);
        System.out.println(test.peek());
        System.out.println("1==" + test.poll());
        System.out.println(test.peek());
        System.out.println("2==" + test.poll());
        System.out.println(test.peek());
        System.out.println("3==" + test.poll());
    }
}
